package org.xxforest.game.core;

import org.xxforest.game.core.assets.XXAssetManager;
import org.xxforest.game.core.scenes.scene2d.XXNode;
import org.xxforest.game.core.scenes.scene2d.XXScreen;
import org.xxforest.game.core.scenes.scene2d.events.type.XXFocusEvent;
import org.xxforest.game.core.scenes.scene2d.selector.XXScheduleSelector;
import org.xxforest.game.core.tween.XXBaseTween;

import com.badlogic.gdx.graphics.OrthographicCamera;

/**
 * 导演类
 * @author 刘海明
 *
 */
public class XXDirector {

	private static XXDirector director ;
	
	private XXScreen screen;
	/**	是否初始化SCREEN*/
	private XXState state ;
	private OrthographicCamera camera ;
	private XXNode focusNode ;
	private XXAssetManager assetManager ;
	
	public void init(){
		assetManager = XX.asset.getAssetManager() ;
	}
	
	public static XXDirector getInstance(){
		if(director == null){
			director = new XXDirector() ;
		}
		return director ;
	}

	public void render(float deltaTime) {
		if(screen != null){
			if(state == XXState.LOAD_RES){
				if(XX.asset.isLoadFinish()){
					state = XXState.INIT_SCREEN;
				}
			}else if(state == XXState.INIT_SCREEN){
				screen.onCreate() ;
				state = XXState.RENDER ;
			}else{
				screen.render(deltaTime) ;
			}
		}
	}

	public void pause() {
		if(screen != null){
			screen.pause() ;
		}
	}

	public void hide() {
		if(screen != null){
			screen.hide() ;
		}
	}

	public void disposeScreen() {
		if(screen != null){
			screen.dispose() ;
		}
	}
	
	public void replaceScreen(XXScreen screen){
		this.screen = screen ;
		this.focusNode = screen ;
		this.screen.initialize() ;
		this.camera = (OrthographicCamera) screen.getCamera() ;
		
		XX.gdx.setInputProcessor(screen);
		this.screen.loadResources(assetManager);
		
		this.state = XXState.LOAD_RES ;
		
	}

	public void resume() {
		if(screen != null){
			screen.resume() ;
		}
	}

	public OrthographicCamera getCamera() {
		return camera;
	}
	
	public void addTween(XXBaseTween<?> tween){
		screen.addTween(tween);
	}
	
	public void addSelector(XXScheduleSelector selector, float sec){
		screen.addSelector(selector, sec);
	}
	
	public XXScreen getScreen(){
		return this.screen ;
	}
	
	public void setFocus(XXNode node){
		XXFocusEvent event = XXFocusEvent.create();
		event.lostFocusNode(focusNode).obtainFocusNode(node);
		if(focusNode != null){
			this.focusNode.fire(event);
		}
		node.fire(event);
		this.focusNode = node ;
		event.dispose() ;
	}
	
	public boolean isFocus(XXNode node){
		return this.focusNode == node ;
	}
	
	public void lostFocus(){
		setFocus(this.screen);
	}
	
	public XXNode getFocus(){
		return this.focusNode ;
	}
	
	enum XXState{
		
		/**	读取资源*/
		LOAD_RES ,
		/**	初始化场景*/
		INIT_SCREEN,
		/**	渲染场景*/
		RENDER,
	}
}
